package com.example.demo.controller;

import cn.idev.excel.EasyExcel;
import cn.idev.excel.ExcelWriter;
import cn.idev.excel.write.metadata.WriteSheet;
import com.example.demo.entity.TestVO;
import com.example.demo.entity.Tests;
import com.example.demo.mapper.TestsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * description
 *
 * @author yangss 2025/03/28 15:38
 */
@RestController
public class TestsController {
    @Autowired
    private TestsMapper testsMapper;
    @GetMapping("/test")
    public void test(){
        final int pageSize = 50000;       // 单次查询 5W 行
        final int maxRowsPerSheet = 1000000; // 单 Sheet 存储 100W 行

        try (ExcelWriter excelWriter = EasyExcel.write("demo.xlsx", TestVO.class).build()) {
            Long lastId = 0L;              // 基于 ID 的分段查询起点
            int currentRow = 0;            // 当前 Sheet 已写入行数
            int sheetIndex = 1;            // Sheet 序号

            // 创建第一个 Sheet
            WriteSheet sheet = EasyExcel.writerSheet("Sheet" + sheetIndex).build();

            while (true) {
                // 分段查询（性能关键！）
                List<Tests> data = testsMapper.selectList(Math.toIntExact(lastId), pageSize);
                if (data.isEmpty()) {
                    break;
                }

                // 写入当前批次数据
                excelWriter.write(data, sheet);
                lastId = data.get(data.size() - 1).getId();  // 更新分段 ID
                currentRow += data.size();

                // Sheet 切换逻辑
                if (currentRow >= maxRowsPerSheet) {
                    sheetIndex++;
                    sheet = EasyExcel.writerSheet("Sheet" + sheetIndex).build();
                    currentRow = 0;
                }
            }
        }
//        testsMapper.selectList(0,5);
//
//        // 创建一个名为“模板”的 sheet 页，并写入数据
//        FastExcel.write(fileName, TestVO.class).sheet("模板").doWrite( testsMapper.selectList(0,5));
    }
    @GetMapping("/exportAll")
    public void exportAll() throws IOException {

        List<Tests> tests = testsMapper.selectList(0, 10000000);

        try (ExcelWriter excelWriter = EasyExcel.write("demo.xlsx", TestVO.class).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
            excelWriter.write(tests, writeSheet);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
